package com.louisgeek.myscanloginserver;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.view.KeyEvent;

import com.louisgeek.myscanloginserver.socket.TcpServer;

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.util.concurrent.Executors;

public class RemoteService extends Service {
    public RemoteService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startSocketServer();
        return super.onStartCommand(intent, flags, startId);
    }

    private void startSocketServer() {
        MySingleton.getInstance().getTcpServer().addOnMsgReceiveListener(new TcpServer.OnMsgReceiveListener() {
            @Override
            public void onMsgReceive(String info) {
                final int keyCode = Integer.parseInt(info);
                Executors.newSingleThreadExecutor().execute(new Runnable() {
                    @Override
                    public void run() {
                        //
                       /* Instrumentation inst = new Instrumentation();
                        inst.sendKeyDownUpSync(keyCode);*/

                        execShellCmd("input keyevent "+ KeyEvent.KEYCODE_ENTER);//home
                    }
                });
            }
        });
    }

    private void execShellCmd(String cmd) {

        try {
            // 申请获取root权限，这一步很重要，不然会没有作用
            Process process = Runtime.getRuntime().exec("su");
            // 获取输出流
            OutputStream outputStream = process.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(
                    outputStream);
            dataOutputStream.writeBytes(cmd + "\n");
            dataOutputStream.flush();
            dataOutputStream.close();
            outputStream.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

}
